package com.ruoyi.common.utils;

/**
 * @Author: wwy
 * @Date: 2019-12-18 16:26
 */
public class PrimaryKeyUtil {
    //其实时间戳
    private final static long START_STMP = 1480166465631L;

    //序列号占用的位数
    private final static long SEQUENCE_BIT = 12;
    //机器标识占用的位数
    private final static long MACHINE_BIT = 5;
    //数据中心占用的位数
    private final static long DATACENTER_BIT = 5;
    //每一部分最大值
    private final static long MAX_DATACENTER_NUM = -1L ^ (-1L << DATACENTER_BIT); // 33
    private final static long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT); // 33
    private final static long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);

    //每一部分向左的位移
    private final static long MACHINE_LEFT = SEQUENCE_BIT;
    private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
    private final static long TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;
    //序号
    private static long sequence = 0L;
    //上一次时间戳
    private static long lastStmp = -1L;

    private static long datacenterId;
    private static long machineId;

    /**
     * 大于这两个值抛出异常
     * @param datacenterId 数据中心id (32之内,0~31)
     * @param machineId 机器标识id (32之内,0~31)
     */
    public  PrimaryKeyUtil(long datacenterId, long machineId){
        if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
            throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0");
        }
        if (machineId > MAX_MACHINE_NUM || machineId < 0) {
            throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0");
        }
        PrimaryKeyUtil.datacenterId = datacenterId;
        PrimaryKeyUtil.machineId = machineId;
        PrimaryKeyUtil.lastStmp = System.currentTimeMillis();
    }

    /**
     * 产生下一个id
     * @return
     */
    public synchronized static long nextId(){
        //当前时间戳
        long currStmp = System.currentTimeMillis();
        //当前时间小于上一次时间(基本不会存在)
        if (currStmp < lastStmp) {
            throw new RuntimeException("Clock moved backwards.  Refusing to generate id");
        }
        //两次时间相等(基本不会存在),序列号自增
        if(currStmp == lastStmp){
            sequence = (sequence + 1) & MAX_SEQUENCE;
            //同一毫秒的序列数已经达到最大
            if (sequence == 0L) {
                currStmp = System.currentTimeMillis();
            }

        }else{
            sequence = 0L;
        }
        lastStmp = currStmp;
        //数据拼接
        return (currStmp - START_STMP) << TIMESTMP_LEFT
                | datacenterId << DATACENTER_LEFT
                | machineId << MACHINE_LEFT
                | sequence;

    }
}